package com.lxw.library.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;



import com.lxw.library.R;

/**
 * Created by Administrator on 2017/4/18.
 */

public class TipDialog extends Dialog {
    Activity activity;

    public TipDialog( Context context) {
        super(context);
        setContentView(R.layout.dialog_tip);
    }

    public void display(String title, String message, int second, boolean isFinish) {
        Window dialogWindow = getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER_VERTICAL);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 0;//设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);
        try {
            show();//显示对话框
            TextView titleTv = findViewById(R.id.titleTv);
            TextView messageTv = findViewById(R.id.tipmessage_tv);
            messageTv.setText(message);
            titleTv.setText(title);
            startTimer(second, isFinish);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void startTimer(final int second, final boolean isFinish) {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (isFinish) {
                    if (null != activity) {
                        try {
                            activity.setResult(Activity.RESULT_OK);
                            activity.finish();
                        } catch (Exception e) {

                        }
                    }
                } else {
                    dismiss();
                }

            }
        };
        handler.sendEmptyMessageDelayed(1, second * 1000);
    }

    public static class Builder {
        TipDialog tipDialog;
        String title, message;
        int showTime;
        boolean isFinish;

        public TipDialog build(Context context) {
            return new TipDialog(context);
        }

        public TipDialog buildTitle(String title) {
            this.title = title;
            return tipDialog;
        }

        public TipDialog buildMsg(String message) {
            this.message = message;
            return tipDialog;
        }

        public TipDialog buildTime(int showTime) {
            this.showTime = showTime;
            return tipDialog;
        }

        public TipDialog buildFinish(boolean isFinish) {
            this.isFinish = isFinish;
            return tipDialog;
        }


        public void disPlay() {
            tipDialog.display(title, message, showTime, isFinish);
        }
    }

}
